/**
 * 
 */
package com.yuyou.fn.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HttpClient工具类
 * @author wuhuoxin 2016年12月15日 下午1:57:48
 *
 */
public class HttpClientUtil2 { 
	
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil2.class);
	
	/**
	 * Post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String post(String url, Map<String,String> params){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		return post(url,params, httpclient);
	}
	
	/**
	 * Post请求
	 * @param url
	 * @param entityStr 直接传输到服务端的一整块参数包装
	 * @return
	 */
	public static String post(String url, String entityStr){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		return post(url,entityStr, httpclient);
	}
	
	/**
	 * Get请求
	 * @param url
	 * @return
	 */
	public static String get(String url){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		return get(url, httpclient);
	}	
	
	/**
	 * 根据指定p12证书和证书密码生成Https Client
	 * @param certFile PKCS12格式证书
	 * @param certPwd
	 * @return https client
	 * @throws Exception
	 */
	public static CloseableHttpClient getSSLClient(InputStream certFileInputStream, String certPwd) throws Exception{
        KeyStore keyStore  = KeyStore.getInstance("PKCS12");
        try {
            keyStore.load(certFileInputStream, certPwd.toCharArray());
        } finally {
        	certFileInputStream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, certPwd.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        return httpclient;
	}
	
	/**
	 * 
	 * @param url
	 * @param params
	 * @param httpclient
	 * @return
	 */
	public static String post(String url, Map<String,String> params, CloseableHttpClient httpclient){
		String rt = null;
		CloseableHttpResponse response = null;			
		try {
			//设置请求配置
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(2000)
					.setSocketTimeout(5000)
					.build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			List <NameValuePair> nvps = new ArrayList <NameValuePair>();
			//填充请求参数
			if(params != null){
				for(Entry<String,String> entry:params.entrySet()){
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
			response = httpclient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    rt = EntityUtils.toString(entity);
		} catch(Exception e){
			logger.error("http post error", e);
			throw new RuntimeException("http post error", e);
		} finally {
			try {if(response!=null) response.close();} catch (IOException e) {}
		    try {if(httpclient!=null) httpclient.close();} catch (IOException e) {}
		}	

		return rt;		
	}
	
	/**
	 * 
	 * @param url
	 * @param entityStr
	 * @param httpclient
	 * @return
	 */
	public static String post(String url, String entityStr, CloseableHttpClient httpclient){
		String rt = null;
		CloseableHttpResponse response = null;		
		try {
			//设置请求配置
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(2000)
					.setSocketTimeout(5000)
					.build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			httpPost.setEntity(new StringEntity(entityStr,"utf-8"));
			response = httpclient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    rt = EntityUtils.toString(entity);
		} catch(Exception e){
			logger.error("http post error", e);
			throw new RuntimeException("http post error", e);
		} finally {
		    try {if(response!=null) response.close();} catch (IOException e) {}
		    try {if(httpclient!=null) httpclient.close();} catch (IOException e) {}
		}	
 
		return rt;
	}
	
	/**
	 * 
	 * @param url
	 * @param httpclient
	 * @return
	 */
	public static String get(String url, CloseableHttpClient httpclient){
		String rt = null;
		CloseableHttpResponse response = null;	
		try {
			//设置请求配置
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(2000)
					.setSocketTimeout(5000)
					.build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			response = httpclient.execute(httpGet);
		    HttpEntity entity = response.getEntity();
		    rt = EntityUtils.toString(entity);
		} catch(Exception e){
			logger.error("http get error", e);
			throw new RuntimeException("http get error", e);
		} finally {
		    try {if(response!=null) response.close();} catch (IOException e) {}
		    try {if(httpclient!=null) httpclient.close();} catch (IOException e) {}		    
		}	
		return rt;
	}	 
	
}
